<template>
  <div class="health-charts">
    <div ref="healthCharts" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup name="PieEcharts" lang="ts">
import * as echarts from 'echarts';

const healthCharts = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const props = defineProps({
  title: {
    type: String,
    required: true,
    default: () => ''
  },
  datas: {
    type: Array<any>,
    required: true,
    default: () => []
  }
});

watch(
  () => props.datas,
  (newDates: any[]) => {
    if (newDates && healthCharts.value) {
      updateChart();
    }
  },
  { immediate: true }
);

const updateChart = () => {
  if (!healthCharts.value) return;

  if (!chartInstance) {
    const chartInstance = echarts.init(healthCharts.value, 'macarons');
    const option = {
      grid: {
        top: '10%',
        right: '5%',
        left: '5%',
        containLabel: true
      },
      tooltip: {
        trigger: 'item',
        backgroundColor: 'rgba(13, 41, 84, 0.7)',
        borderColor: 'rgba(0, 146, 98, 0.3)',
        textStyle: {
          color: '#000'
        }
      },
      legend: {
        show: true,
        orient: 'horizontal',
        bottom: 10,
        textStyle: {
          color: '#000'
        }
      },
      series: [
        {
          name: props.title,
          type: 'pie',
          radius: ['36%', '68%'],
          center: ['50%', '50%'],
          itemStyle: {
            borderRadius: 6,
            // borderColor: 'rgba(13, 41, 84, 0.7)',
            borderWidth: 2
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b} : {c}台',
            color: '#000',
            fontSize: 14
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          data: props.datas,
          color: ['#FE6866', '#03c782', '#FF8800', '#adadad']
        }
      ]
    };
    chartInstance.setOption(option);
    window.addEventListener('resize', () => chartInstance?.resize());
  }
};

onMounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    window.removeEventListener('resize', () => chartInstance?.resize());
  }
});
</script>

<style scoped lang="scss">
.health-charts {
  width: 100%;
  height: calc(100% - 30px);
}
</style>
